from google.appengine.ext.db import Key

from dvk.main.models.barcodes import Barcode, Product

from django.http import HttpResponse

import elementtree.ElementTree as ET
from elementtree.ElementTree import tostring

def __get_error_txt(code, message, details):
    return tostring(ET.Element('error',
            code   =code,
            message=message,
            details=details), encoding='utf-8')

def __get_ok_result(barcode):
    barcode_xml = ET.Element('barcode', id=barcode.key().name())
    if barcode.product:
        ET.SubElement(barcode_xml, 'info').text = barcode.product.description
    return tostring(barcode_xml, encoding='utf-8')

def get_barcode(request):
    code = request['code']
    barcode = Barcode.get(Key.from_path('Barcode', code))
    if barcode == None:
        return HttpResponse(
            __get_error_txt(
                '0',
                'Barcode not fount',
                'Barcode not fount, please contact customer support'),
                mimetype='text/plain')
    else:
        #TODO to_xml can be used
        return HttpResponse(__get_ok_result(barcode), mimetype='text/plain')

def put_barcode(request):
    barcode = request['barcode']
    info    = request['info'   ]
    barcode_obj = Barcode.get_or_insert(barcode)
    if not barcode_obj.product:
        product = Product(description=info)
        product.put()
        barcode_obj.product = product
        barcode_obj.put()
    return HttpResponse('put ok', mimetype='text/plain')